﻿using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace MissionImpossible.Custom
{
  public partial class YearInputField : TextBox
  {
    private const int FirstFilmYear = 1894;


    public event EventHandler<YearValidationEvent> YearValidated;
    public YearInputField()
    {
      InitializeComponent();
      Validating += YearInputFieldcs_Validating;
      KeyPress += YearInputFieldcs_KeyPress;
    }

    void YearInputFieldcs_KeyPress(object sender, KeyPressEventArgs e)
    {
      e.Handled = !(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar));
    }

    void YearInputFieldcs_Validating(object sender, CancelEventArgs e)
    {
      bool correct = Text == string.Empty || IsCorrectYear(Text);
      EventHandler<YearValidationEvent> handler = YearValidated;
      if(handler != null)
      {
        handler(this, new YearValidationEvent(correct, FirstFilmYear, DateTime.Today.Year));
      }
    }

    private bool IsCorrectYear(string input)
    {
      int result;
      bool parseOk = Int32.TryParse(input, out result);
      if(!parseOk)
      {
        return false;
      }


      return result >= FirstFilmYear && result <= DateTime.Today.Year;
    }
  }
}
